package com.pig4cloud.pig.juhe.admin.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtil;
import com.pig4cloud.pig.juhe.admin.config.JuheProperties;
import com.pig4cloud.pig.juhe.admin.mapper.JuheChannelAttrValueMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheChannelInfoMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheGameChannelMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheGameInfoMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuheGamePageMapper;
import com.pig4cloud.pig.juhe.admin.mapper.JuhePackMapper;
import com.pig4cloud.pig.juhe.admin.service.AsyncService;
import com.pig4cloud.pig.juhe.api.entity.JuheChannelInfo;
import com.pig4cloud.pig.juhe.api.entity.JuheGameChannel;
import com.pig4cloud.pig.juhe.api.entity.JuheGameInfo;
import com.pig4cloud.pig.juhe.api.entity.JuheGamePage;
import com.pig4cloud.pig.juhe.api.entity.JuhePack;
import com.pig4cloud.pig.juhe.api.util.ApkIconUtil;
import com.pig4cloud.pig.juhe.api.util.ApkInfo;
import com.pig4cloud.pig.juhe.api.util.ApkUtil;
import com.pig4cloud.pig.juhe.api.util.AppUtils;
import com.pig4cloud.pig.juhe.api.util.Constant;
import com.pig4cloud.pig.juhe.api.vo.AsyncPackInfoData;
import com.pig4cloud.pig.juhe.api.vo.JuheChannelAttrValueVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yuwenfeng
 * @description: 打包工具定时任务
 * @date 2021/9/28 19:07
 */
@Component
@AllArgsConstructor
@Slf4j
public class PythonPackJob {

	private final JuheGamePageMapper juheGamePageMapper;

	private final JuhePackMapper juhePackMapper;

	private final JuheGameChannelMapper juheGameChannelMapper;

	private final JuheGameInfoMapper juheGameInfoMapper;

	private final JuheChannelAttrValueMapper juheChannelAttrValueMapper;

	private final JuheChannelInfoMapper juheChannelInfoMapper;

	private final AsyncService asyncService;

	private final JuheProperties juheProperties;

	/*@Scheduled(cron = "* 0/2 * * * ?")*/ // 读取遗漏的包的信息
	public void fetchApkInfoJob() {
		log.info("fetchApkInfoJob----start------");
		List<JuheGamePage> list = juheGamePageMapper.selectList(new QueryWrapper<JuheGamePage>().eq("page_status", Constant.PAGE_STATUS_WAIT).orderByAsc("create_time"));
		if (CollectionUtils.isNotEmpty(list)) {
			for (JuheGamePage gamePage : list) {
				String apkName = gamePage.getPageUrl().substring(gamePage.getPageUrl().lastIndexOf(StrUtil.SLASH) + 1);
				String apkPath = juheProperties.getJuheFileDir() + Constant.FILE_PACKAGE_IN + File.separator + apkName;
				try {
					ApkInfo apkInfo = new ApkUtil().getApkInfo(apkPath);
					log.info("apkInfo:{}", JSONObject.toJSONString(apkInfo));
					if (null != apkInfo && StringUtils.isNotBlank(apkInfo.getSuitableApplicationIcon())) {
						String extensionName = apkInfo.getSuitableApplicationIcon().substring(apkInfo.getSuitableApplicationIcon().lastIndexOf('.') + 1);
						if (Constant.PNG.equalsIgnoreCase(extensionName)) {
							String iconName = DateUtil.dateToString() + AppUtils.getAppId() + StrUtil.DOT + Constant.PNG;
							ApkIconUtil.extractFileFromApk(apkPath, apkInfo.getSuitableApplicationIcon(), juheProperties.getJuheFileDir() + Constant.FILE_IMAGES_PATH + File.separator + iconName);
							gamePage.setPageInfo(JSON.toJSONString(apkInfo));
							gamePage.setPagePackage(apkInfo.getPackageName());
							gamePage.setPageName(apkInfo.getApplicationLable());
							gamePage.setPageIcon(juheProperties.getJuheFilePath() + Constant.FILE_IMAGES_PATH + StrUtil.SLASH + iconName);
							gamePage.setPageVersion(apkInfo.getVersionName());
							gamePage.setPageStatus(Constant.PAGE_STATUS_SUCC);
						} else {
							log.error("母包记录" + gamePage.getPageId() + "：{}", "图片无法识别");
							gamePage.setPageStatus(Constant.PAGE_STATUS_FAIL);
						}
					} else {
						log.error("母包记录" + gamePage.getPageId() + "：{}", "读包失败");
						gamePage.setPageStatus(Constant.PAGE_STATUS_FAIL);
					}
				} catch (Exception e) {
					log.error("母包记录" + gamePage.getPageId() + "：", e);
					gamePage.setPageStatus(Constant.PAGE_STATUS_FAIL);
				} finally {
					gamePage.setUpdateTime(new Date());
					juheGamePageMapper.updateById(gamePage);
				}
			}
		}
	}

	/*@Scheduled(cron = "* 0/2 * * * ?")*/ // 每2分钟处理渠道分包
	public void packChannelApkJob() {
		log.info("packChannelApkJob----start------");
		List<Long> gameIds = juhePackMapper.selectListGroupByGame();
		if (CollectionUtils.isNotEmpty(gameIds)) {
			List<AsyncPackInfoData> packDataList = new ArrayList<AsyncPackInfoData>();
			AsyncPackInfoData packData;
			JuheGameInfo gameInfo;
			for (Long gameId : gameIds) {
				List<JuhePack> packList = juhePackMapper.selectList(new QueryWrapper<JuhePack>().eq("game_id", gameId).eq("pack_status", Constant.PACKAGE_STATUS_WAIT).orderByAsc("create_time"));
				gameInfo = juheGameInfoMapper.selectOne(new QueryWrapper<JuheGameInfo>().eq("game_id", gameId).eq("del_flag", Constant.DEL_NO));
				if (null == gameInfo) {
					continue;
				}
				if (CollectionUtils.isNotEmpty(packList)) {
					JuheGamePage gamePage;
					List<JuheChannelAttrValueVo> attrValueList;
					JuheChannelInfo channelInfo;
					JuheGameChannel gameChannel;
					for (JuhePack pack : packList) {
						gamePage = juheGamePageMapper.selectOne(new QueryWrapper<JuheGamePage>().eq("page_id", pack.getPageId()).eq("game_id", gameInfo.getGameId()).eq("page_status", Constant.PAGE_STATUS_SUCC));
						if (null == gamePage) {
							continue;
						}
						channelInfo = juheChannelInfoMapper.selectById(pack.getChannelId());
						if (null == channelInfo) {
							continue;
						}
						gameChannel = juheGameChannelMapper.selectOne(new QueryWrapper<JuheGameChannel>().eq("channel_id", pack.getChannelId()).eq("game_id", pack.getGameId()).eq("del_flag", Constant.DEL_NO));
						if (null == gameChannel) {
							continue;
						}
						attrValueList = juheChannelAttrValueMapper.selectAttrValueVoList(pack.getChannelId(), gameInfo.getGameId());
						if (CollectionUtils.isEmpty(attrValueList)) {
							continue;
						}
						packData = new AsyncPackInfoData();
						packData.setPackId(pack.getPackId());
						packData.setAttrValueList(attrValueList);
						packData.setChannelInfo(channelInfo);
						packData.setGamePage(gamePage);
						packData.setGameInfo(gameInfo);
						packData.setGameChannel(gameChannel);
						packDataList.add(packData);
					}
					asyncService.packChannelApk(packDataList);
				}
			}
		}
	}
}
